/**
 * 
 */
package table;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.EventObject;
import java.util.List;
import javax.swing.JComboBox;
import javax.swing.JTable;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.event.EventListenerList;
import javax.swing.table.TableCellEditor;
import database.DataType;
/**
 * @author Ken
 *
 */
public class ComboboxEditor extends JComboBox implements TableCellEditor{
	protected EventListenerList m_listenerList = new EventListenerList();
    protected ChangeEvent m_changeEvent = new ChangeEvent(this);
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public ComboboxEditor() {
		super();
		DataType data = DataType.GetInstance();
		List<String> types = data.get_dataType();
		for (int i = 0; i < types.size(); i++) {
			addItem(types.get(i));
		}
		addActionListener(new ActionListener() {			
			@Override
			public void actionPerformed(ActionEvent e) {
				fireEditingStopped();
			}
		});
	}
	
	@Override
	public void addCellEditorListener(CellEditorListener l) {
		m_listenerList.add(CellEditorListener.class, l);		
	}

	@Override
	public void cancelCellEditing() {
		fireEditingCanceled();
	}

	private void fireEditingCanceled() {
		CellEditorListener listener;
        Object[] listeners = m_listenerList.getListenerList();
        for(int i=0; i< listeners.length; i++){
            if(listeners[i] == CellEditorListener.class){
                listener = (CellEditorListener) listeners[i+1];
                listener.editingCanceled(m_changeEvent);
            }
        }
	}

	@Override
	public Object getCellEditorValue() {
		DataType data = DataType.GetInstance();
		List<String> types = data.get_dataType();
		return types.get(getSelectedIndex());
	}

	@Override
	public boolean isCellEditable(EventObject anEvent) {
		return true;
	}

	@Override
	public void removeCellEditorListener(CellEditorListener l) {
		m_listenerList.remove(CellEditorListener.class, l);
	}

	@Override
	public boolean shouldSelectCell(EventObject anEvent) {
		return true;
	}

	@Override
	public boolean stopCellEditing() {
		fireEditingStopped();
        return true;
	}

	private void fireEditingStopped() {
		CellEditorListener listener;
        Object[] listeners = m_listenerList.getListenerList();
        for(int i=0; i<listeners.length; i++){
            if(listeners[i] == CellEditorListener.class){
                listener = (CellEditorListener) listeners[i+1];
                listener.editingStopped(m_changeEvent);
            }
        }
	}

	@Override
	public Component getTableCellEditorComponent(JTable table, Object value,
			boolean isSelected, int row, int column) {
		boolean isInt = value.toString().equals("int");
        setSelectedIndex(isInt?0:1);
        return this;
	}

}
